package xml;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLLoader {
	private Document xmlDoc;
	public XMLLoader(String absoluteFilePath) throws ParserConfigurationException, SAXException, IOException{
		loadXML(absoluteFilePath);
	}
	public void loadXML(String absoluteFilePath) throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true); // never forget this!
		DocumentBuilder builder = factory.newDocumentBuilder();
		xmlDoc = builder.parse(absoluteFilePath);
	}
	public Object evaluate(String expression) throws XPathExpressionException {
		XPath xPath = XPathFactory.newInstance().newXPath();
		return evaluate(xPath.compile(expression));
	}
	public Object evaluate(XPathExpression compiledExpression) throws XPathExpressionException{
		return  compiledExpression.evaluate(xmlDoc ,XPathConstants.NODESET);
	}

	public static void main(String[] args) {
		try {
			XMLLoader loader = new XMLLoader("C:/Code/balance-ranking/xml/test.xml");
			NodeList games = (NodeList) loader.evaluate("/data/game");
			for (int i = 0; i < games.getLength(); i++) {
				Node game = (Node) games.item(i);
				System.out.println(game.getAttributes().getNamedItem("environment").getNodeValue());
			}
			NodeList players = (NodeList) loader.evaluate("/data/game/player");
			for (int i = 0; i < players.getLength(); i++) {
				Node player = (Node) players.item(i);
				System.out.println(player.getAttributes().getNamedItem("id").getNodeValue());
			}
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
}
